package com.ruoyi.business.api;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.business.domain.ReceivingNote;
import com.ruoyi.business.service.ReceivingNoteService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;

/**
 * @author JerryLu
 * @date 2024/8/2 9:18
 * @description 金蝶服务接口
 */
@Component
@Slf4j
public class KingDeeApi {

    @Autowired
    private ReceivingNoteService noteService;

    private RestTemplate restTemplate;

    /**
     * 同步金蝶系统中审核通过的 【采购收料通知单】
     *
     * @param jsonObject1
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author JerryLu
     * @date 2024/8/21 16:10
     */
    public AjaxResult syncReceivingNoteInfo(JSONObject jsonObject1) {
        try {
            String url = "https://huaze.kdgalaxy.com/kapi/v2/im/im_purreceivebill/getList";
            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json; charset=utf-8");
            headers.set("Accept-Charset", "utf-8");
            headers.add("accesstoken", this.getAccessToken());
            headers.add("Idempotency-Key", "String.valueOf(timestamp)");
            headers.add("x-acgw-identity", "getPaySign(content, timestamp)");
            JSONObject json = new JSONObject();
            JSONObject jsonObject = new JSONObject();
            String time = DateUtils.getDate();
            json.put("start_biztime", time);
            json.put("end_biztime", time);
            json.put("billstatus", "C");
            jsonObject.put("data", json);
            jsonObject.put("pageSize", 1000);
            jsonObject.put("pageNo", 10);
            HttpEntity<String> entity = new HttpEntity<>(jsonObject.toString(), headers);

            restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
            JSONObject jsonResult = JSON.parseObject(response.getBody());
            if (Objects.equals(jsonResult.get("status"), true) && Objects.equals(jsonResult.getString("errorCode"), "")) {
                ReceivingNote note = JSON.parseObject(response.getBody(), ReceivingNote.class);
                noteService.save(note);

                return AjaxResult.success();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }

        return AjaxResult.error();
    }

    private String getAccessToken() {
        return "";
    }
}
